<?php

require_once('../lib/spyc-0.2.5/spyc.php');
require_once( $CFG->dirroot . 'mod/folio/model/page.php');
require_once( $CFG->dirroot . 'mod/folio/model/tags.php');

/**
 * This is used for templating in pages. Mainly called by /html/new.php
 */
class folio_page_template{

    function path() {
      return '../template/templates.yaml';
    }

    /**
     * Get an array of templates
     */
    public function SelectTemplates() {
        global $CFG;

    // Parse yaml config data
    $yaml = Spyc::YAMLLoad(folio_page_template::path());
    $templates = array();

        // Build a list of template names.
    foreach( $yaml as $key => $value )
       $templates[$key] = $value;

    return $templates;
    }

    /**
    * Output YAML
    */
    public function printYAML() {
        $yaml = Spyc::YAMLLoad(folio_page_template::path());
        var_dump( $yaml );
        die('Yaml printed');
    }

    /**
    * Call to retrieve input from _POST and make the corresponding pages
    * Assume that we have permissions.
    * @param folio_page $user Location of the page
    * @param string $template_name Name of the YAML template.
    * @param string $page_name Optional, only create one page in the template.
    */
    public function TemplateFactory( folio_user $user, $template_name, $page_name = '' ) {
        global $FOLIO_CFG;

        $prefix = 'folio_page_template';
        $yaml = Spyc::YAMLLoad(folio_page_template::path());
        $pages = array();

        // Ensure valid template name.
        if( !isset( $yaml[$template_name] ) )
            trigger_error('Invalid template "' . $template_name .
              '" passed to folio_page_template::htmlUpdateFromPost', E_USER_ERROR);

        // Load template.
        $template = $yaml[$template_name];
        $homepage = folio_page::SelectHomepage($user);

        // Create homepage
        if( $page_name == '' OR $page_name == $template['homepage']['title'] ) {
            $homepage = folio_page_template::PageFactory($user,
                                                $template['homepage']['title'],
                                                $template['homepage'], false);
            $pages[$homepage->title] = $homepage;
        }

        // Fail if homepage isn't set yet.
        if( $homepage == false )
            trigger_error('You can not create a new page without having first created' .
                          ' a homepage.', E_USER_ERROR);

        // Create Main pages.
        if( count($template['pages']) > 0 ) {
            foreach( $template['pages'] as $key=>$value ) {
                // See if we should create all pages, or only a single one.
                if( $page_name == '' OR $page_name == $key ) {
                    
                    // Set parentpage if needed.
                    if( $value['parent_page'] == null || $value['parent_page'] == '' )
                        $p = folio_page_template::PageFactory($user, $key, $value, $homepage);
                    else {
                        $parent_page = folio_page::SelectWhereTitleAndUsername( 
                                        $value['parent_page'], $user->username );
                        if( $parent_page === false )
                            $p = folio_page_template::PageFactory($user, $key, $value, $homepage);
                        else
                            $p = folio_page_template::PageFactory($user, $key, $value, $parent_page);
                    }
                    $pages[$p->title] = $p;
                }
            }
        }

        // Create optional pages.
        if( count($template['optional_pages']) > 0 ) {
            foreach( $template['optional_pages'] as $key=>$value ) {
                // Create only a single optional page at a time, and not when first initializing a portfolio.
                if( $page_name == $key ) {
                    // Set parentpage if needed
                    if( $value['parent_page'] == null || $value['parent_page'] == '' )
                        $p = folio_page_template::PageFactory($user, $key, $value, $homepage);
                    else {
                        $parent_page = folio_page::SelectWhereTitleAndUsername( 
                                        $value['parent_page'], $user->username );
                        if( $parent_page === false )
                            $p = folio_page_template::PageFactory($user, $key, $value, $homepage);
                        else
                            $p = folio_page_template::PageFactory($user, $key, $value, $parent_page);
                    }
                    $pages[$p->title] = $p;
                }
            }
        }

        return $pages;
    }

    /**
     * Create a single page
     *
     * @param folio_user $user
     * @param string $page_title
     * @param array $template The template for the page (homepage or other)
     * @param folio_page $parentpage False if this is a homepage.
     * @return folio_page The New page
     */
    private function PageFactory( folio_user $user, $page_title, $template, $parentpage ) {

        // Find the old page (if it exists)
        $page = false;
        if( $parentpage == false )
            $page = folio_page::SelectHomepage($user);
        else
            $page = folio_page::SelectWhereTitleAndUsername($page_title, $user->username);

        // Build new page (or update)
        if( $page == false ){
            // No existing page, create a new one.

            if( $parentpage == false ) {
                // Creating a homepage. We don't have a page ident yet,
                //  and so can't set it in the newpagefactory.  Fake it &
                //  then update later.

                $page = folio_page::NewPageFactory($user,
                    $page_title, $template['body'], $template['format_ident'],
                    1 );
                $page->parentpage_ident = $page->page_ident;

            } else {
                // Normal
                $page = folio_page::NewPageFactory($user,
                    $page_title, $template['body'], $template['format_ident'],
                    $parentpage->page_ident );
            }
        } else {
            // Existing page, update.
            $page->title = $page_title;
            $page->body = $template['body'];
            $page->format_ident = $template['format_ident'];
        }

        // At this point, we have the page, though it may need to be saved.
        // Continue by adding all of the peripheral stuff like attachments.


        $page->help = $template['help'];

        // Add attachments.
        if( $template['attachments'] != NULL ) {
            foreach( $template['attachments'] as $attachment ) {
                $key = '';
                if( $attachment['style'] == 'decoration' ) {
                    // Load a new dec into the db.
                    $d = new folio_decoration( );
                    $d->page_ident = $page->page_ident;
                    $d->type = $attachment['type'];
                    $d->text = $attachment['text'];
                    $d = folio_decoration::Insert($d);
                    $key = 'decoration' . $d->decoration_ident;

                } elseif( $attachment['style'] == 'artifact' ) {
                    // Load a new artifact into the db.

                    // First, find the resource mapped to the artifact
                    $r = folio_resource::SelectWhereKey(
                        folio_resource::encodeKey(
                            $attachment['item_ident'], $attachment['item_type'], $attachment['item_owner']
                            ));

                    if( $r == false )
                        trigger_error("Unable to load resource " . $attachment['item_ident'], E_USER_ERROR);

                    // Now, create the related artifact.
                    $a = folio_artifact::CreateArtifactsFromResources(
                            $r ,$page->user_ident, $page->page_ident );

                    if( count( $a ) == 0  )
                        trigger_error('Unable to create artifact for ' . $attachment['item_ident']);

                    // Update the rest of the artifact
                    $a = $a[0];
                    $a->title = $attachment['title'];
                    $a->text = $attachment['text'];
                    $a->reflection = $attachment['reflection'];
                    folio_artifact::Update( $a );
                    $key = 'artifact' . $a->artifact_ident;
                } else {
                    trigger_error('Unable to load style "' . $attachment['style'] .
                                  '", unknown type.', E_USER_ERROR);
                }

                // Add the key the page record, setting order.
                if( strlen($page->attachments) > 0 )
                    $page->attachments = $page->attachments . ',' . $key;
                else
                    $page->attachments = $key;
            }
        } // If Attachments.


        // Update tags.
        if ( $template['tags'] != NULL ) {
            // Replace $yearterm with Fall2008
            if( date('m') < 6 ) 
                $yt='Spring' . date('Y');
            elseif( date('m') < 8 ) 
                $yt='Summer' . date('Y');
            else
                $yt='Fall' . date('Y');
            $template['tags'] = str_replace( '$yearterm', $yt, $template['tags'] );
        
            folio_tags::Update($page, $template['tags']);
        }
        $page->Update();
        return $page;
    }
}
?>
